package cn.onlineclass.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

@WebServlet("/CodeServlet")
public class CodeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String[] strs ={"a","b","c","d","e","f","g","h","i","j",
                "k","l","m","n","o","p","q","r","s","t","u","v",
                "w","x","y","z","2","3","4","5","6","7","8","9"};
        int w = 150;
        int h = 50;
        Random r = new Random();
        //创建空白图片
        BufferedImage imge = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
        //获取画笔
        Graphics2D g = (Graphics2D) imge.createGraphics();
        //设置画笔颜色
        g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
        //用画笔绘制背景
        g.fillRect(0,0,w,h);
        //绘制8条干扰线条
        for(int i=0;i<8;i++){
            g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
            g.drawLine(r.nextInt(100),r.nextInt(30),r.nextInt(100),r.nextInt(30));
        }
        int x=30;
        int y=30;
        g.setColor(Color.green);
        g.setFont(new Font("楷体",Font.BOLD,30));

        String str ="";
        for (int i=0;i<4;i++){
            String st = strs[r.nextInt(strs.length)];
            int jd = r.nextInt(90)-45;
            double hd = jd * Math.PI / 180;
            g.rotate(hd,x,y);
            g.drawString(st,x,y);
            g.rotate(-hd,x,y);
            x += 25;
            str += st;
        }
        request.getSession().setAttribute("code",str);
        response.setContentType("imge/jpeg");
        OutputStream out = response.getOutputStream();
        ImageIO.write(imge,"jpg",out);
        out.close();
    }
}
